<template>
  <view class="supplier-detail">
    <!-- 基本信息卡片 -->
    <view class="info-card">
      <view class="card-header">
        <text class="card-title">基本信息</text>
        <view class="status-tag" :class="supplierInfo.status === '0' ? 'active' : 'inactive'">
          {{ supplierInfo.status === '0' ? '正常' : '停用' }}
        </view>
      </view>
      
      <view class="info-content">
        <view class="info-item">
          <text class="info-label">供货商名称</text>
          <text class="info-value">{{ supplierInfo.supplierName || '-' }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">供货商类型</text>
          <text class="info-value">{{ getSupplierTypeText() }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">联系人</text>
          <text class="info-value">{{ supplierInfo.contactPerson || '-' }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">联系电话</text>
          <text class="info-value">{{ supplierInfo.contactPhone || '-' }}</text>
        </view>
        
        <view class="info-item" v-if="supplierInfo.supplierType === '0'">
          <text class="info-label">身份证号</text>
          <text class="info-value">{{ formatIdCard(supplierInfo.idCard) }}</text>
        </view>
        
        <view class="info-item" v-if="supplierInfo.supplierType !== '0'">
          <text class="info-label">营业执照</text>
          <text class="info-value">{{ supplierInfo.businessLicense || '-' }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">创建时间</text>
          <text class="info-value">{{ formatTime(supplierInfo.createTime) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 资质文件 -->
    <view class="info-card" v-if="supplierInfo.qualificationFile">
      <view class="card-header">
        <text class="card-title">资质文件</text>
      </view>
      <view class="file-content">
        <image 
          :src="getImageUrl(supplierInfo.qualificationFile)" 
          class="cert-image" 
          mode="aspectFit"
          @click="previewImage(getImageUrl(supplierInfo.qualificationFile))"
          @error="onImageError"
        ></image>
        <text class="file-path">{{ supplierInfo.qualificationFile }}</text>
      </view>
    </view>
    
    <!-- 备注信息 -->
    <view class="info-card" v-if="supplierInfo.remark">
      <view class="card-header">
        <text class="card-title">备注信息</text>
      </view>
      <view class="remark-content">
        <text class="remark-text">{{ supplierInfo.remark }}</text>
      </view>
    </view>
    
    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <button class="edit-btn" @click="editSupplier">
        <uni-icons type="compose" size="18" color="#fff"></uni-icons>
        <text class="btn-text">编辑</text>
      </button>
      <button class="delete-btn" @click="deleteSupplier">
        <uni-icons type="trash" size="18" color="#ff4d4f"></uni-icons>
        <text class="btn-text" style="color: #ff4d4f;">删除</text>
      </button>
    </view>
  </view>
</template>

<script>
import { getSupplier, delSupplier } from '@/api/system/supplier.js'
import config from '@/config'

export default {
  data() {
    return {
      supplierId: null,
      supplierInfo: {}
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.supplierId = options.id
      this.loadSupplierInfo()
    }
  },
  
  methods: {
    // 获取图片完整URL
    getImageUrl(path) {
      if (!path) return ''
      
      // 如果已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path
      }
      
      // 如果是base64图片，直接返回
      if (path.startsWith('data:image')) {
        return path
      }
      
      // 如果是临时文件路径（本地预览）
      if (path.startsWith('blob:') || path.indexOf('tmp') > -1 || path.startsWith('wxfile://')) {
        return path
      }
      
      // 如果是相对路径，拼接baseUrl
      if (path.startsWith('/')) {
        return config.baseUrl + path
      }
      
      // 否则直接返回
      return path
    },
    
    // 图片加载失败处理
    onImageError(e) {
      console.error('图片加载失败:', e.detail.errMsg)
    },
    
    // 加载供货商详情
    async loadSupplierInfo() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await getSupplier(this.supplierId)
        
        if (response.code === 200) {
          this.supplierInfo = response.data || {}
        } else {
          uni.showToast({
            title: '加载失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载供货商详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 获取供货商类型文本
    getSupplierTypeText() {
      const typeMap = {
        '0': '个人',
        '1': '合作社',
        '2': '农贸市场'
      }
      return typeMap[this.supplierInfo.supplierType] || '未知'
    },
    
    // 格式化身份证号
    formatIdCard(idCard) {
      if (!idCard) return '-'
      if (idCard.length === 18) {
        return idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2')
      }
      return idCard
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return '-'
      return time.split(' ')[0]
    },
    
    // 预览图片
    previewImage(url) {
      uni.previewImage({
        urls: [url],
        current: 0
      })
    },
    
    // 编辑供货商
    editSupplier() {
      uni.navigateTo({
        url: `/pages/supplier/edit?id=${this.supplierId}`
      })
    },
    
    // 删除供货商
    deleteSupplier() {
      uni.showModal({
        title: '提示',
        content: '确定要删除该供货商吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...' })
              
              const response = await delSupplier(this.supplierId)
              
              if (response.code === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                
                setTimeout(() => {
                  uni.navigateBack()
                }, 1500)
              } else {
                uni.showToast({
                  title: response.msg || '删除失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              console.error('删除供货商失败:', error)
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            } finally {
              uni.hideLoading()
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.supplier-detail {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 信息卡片 */
.info-card {
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.card-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.status-tag {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.status-tag.active {
  background: #e6f7ff;
  color: #1890ff;
}

.status-tag.inactive {
  background: #fff1f0;
  color: #ff4d4f;
}

/* 信息内容 */
.info-content {
  padding: 20rpx 30rpx;
}

.info-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f8f8f8;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  width: 180rpx;
  font-size: 28rpx;
  color: #999;
}

.info-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

/* 文件内容 */
.file-content {
  padding: 30rpx;
}

.cert-image {
  width: 100%;
  max-height: 400rpx;
  border-radius: 8rpx;
  background: #f8f8f8;
}

.file-path {
  display: block;
  margin-top: 16rpx;
  font-size: 24rpx;
  color: #999;
  word-break: break-all;
}

/* 备注内容 */
.remark-content {
  padding: 30rpx;
}

.remark-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

/* 底部操作按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  gap: 30rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.edit-btn,
.delete-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  font-size: 32rpx;
  border: none;
}

.edit-btn {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  color: #fff;
}

.delete-btn {
  background: #fff;
  border: 2rpx solid #ff4d4f;
}

.btn-text {
  font-size: 30rpx;
}
</style>